﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using ORM.Areas.Admin.Controllers;
using ORM.Business.Feedbacks;
using ORM.Business.Interfaces;
using ORM.Business.Models;
using ORM.Business.Models.Caching;
using ORM.Business.Models.Entities;
using ORM.Common;
using ORM.Common.Caching;
using ORM.Common.Helpers;
using ORM.Common.Logging;
using ORM.Models.FileManagement;
using ORM.Resources;
using ORM.Areas.Admin.ViewModels.ManageCategories;
using ORM.Controllers;
using ORM.Framework.Filters;
using ORM.Web.Models;

namespace ORM.Areas.Admin.Controllers
{
    /// <summary>
    /// Handles categories management pages
    /// </summary>
    [PermissionAuthorize(Permissions = KeyObject.Permission.ManageCategories)]
    public class ManageCategoriesController : AdminControllerBase
    {
        private IUploadHandler _uploadHandler;
        private IModelRepository _modelRepository;
        private IManufacturerRepository _manufacturerRepository;
        private IDeviceRepository _deviceRepository;
        private IGuideTypeRepository _guideTypeRepository;
        private OrmEntities ORMdb = new OrmEntities();

        public ManageCategoriesController(IGuideTypeRepository guideTypeRepository,IDeviceRepository deviceRepository, IManufacturerRepository manufacturerRepository, IModelRepository modelRepository, IUploadHandler uploadHandler)
        {
            _deviceRepository = deviceRepository;
            _manufacturerRepository = manufacturerRepository;
            _modelRepository = modelRepository;
            _uploadHandler = uploadHandler;
            _guideTypeRepository = guideTypeRepository;
        }


        #region Manufacturer Categories
        public ViewResult ManageManufacturerCategories()
        {
            ListManufacturerCategoryViewModel vm = new ListManufacturerCategoryViewModel();
            vm.Manufacturers = _manufacturerRepository.GetAllManufacturer().Data;
            return View(vm);
        }


        [HttpPost]
        public ActionResult DeleteManufacturerCategory(int id)
        {
            Feedback feedback = _manufacturerRepository.DeleteManufacturerCategory(id);
            if (feedback.Success)
            {
                // Remove from cache
                ReferenceDataCache.ManufacturerCollection.RemoveAll(i => i.Id == id);

                SetMessage("Manufacturer Category has been deleted successfully", MessageType.Success);
            }
            else
            {
                SetMessage(feedback.Message, MessageType.Error);
            }

            // Redirect to current page after deleting
            return Redirect(Request.UrlReferrer.AbsoluteUri);
        }

        public ViewResult CreateManufacturerCategory()
        {
            return View(new InsertManufacturerCategoryViewModel { Manufacturer = new Manufacturer() });
        }

        [HttpPost]
        public ActionResult CreateManufacturerCategory(InsertManufacturerCategoryViewModel vm)
        {
            if (ModelState.IsValid)
            {
                Feedback<Manufacturer> feedback = _manufacturerRepository.InsertManufacturer(vm.Manufacturer);

                if (feedback.Success)
                {
                    Manufacturer exist = ReferenceDataCache.ManufacturerCollection.FirstOrDefault(i => i.Id == feedback.Data.Id);
                    if (exist == null)
                    {
                        ReferenceDataCache.ManufacturerCollection.Add(feedback.Data);
                        ReferenceDataCache.ManufacturerCollection.Sort((c1, c2) => c1.Name.CompareTo(c2.Name));
                    }

                    SetMessage("Manufacturer has been inserted successfully", MessageType.Success);

                    return RedirectToAction("ManageManufacturerCategories");
                }
                else
                {
                    SetMessage(feedback.Message, MessageType.Error);
                }
            }

            return View(vm);
        }

        public ActionResult EditManufacturerCategory(int id = 0)
        {
            var feedback = _manufacturerRepository.GetManufacturerCategoryDetails(id);
            if (feedback.Success)
            {
                return View(new InsertManufacturerCategoryViewModel() { Manufacturer = feedback.Data });
            }
            else
            {
                SetMessage(feedback.Message, MessageType.Error);
                return RedirectToAction("ManageManufacturerCategories");
            }
        }
        [HttpPost]
        public ActionResult EditManufacturerCategory(InsertManufacturerCategoryViewModel vm)
        {
            if (ModelState.IsValid)
            {
                // Call repository to perform insert
                Feedback<Manufacturer> feedback = _manufacturerRepository.UpdateManufacturerCategory(vm.Manufacturer);
                if (feedback.Success)
                {
                    Manufacturer exist = ReferenceDataCache.ManufacturerCollection.FirstOrDefault(i => i.Id == feedback.Data.Id);
                    if (exist != null)
                    {
                        ReferenceDataCache.ManufacturerCollection.Remove(exist);
                        ReferenceDataCache.ManufacturerCollection.Add(feedback.Data);
                        ReferenceDataCache.ManufacturerCollection.Sort((c1, c2) => c1.Name.CompareTo(c2.Name));
                    }

                    SetMessage("Manufacturer Category has been updated successfully", MessageType.Success);

                    return RedirectToAction("ManageManufacturerCategories");
                }
                else
                {
                    SetMessage(feedback.Message, MessageType.Error);
                }
            }

            return View(vm);
        }

        #endregion

        #region Model Categories
        public ViewResult ManageModelCategories()
        {
            ListModelCategoryViewModel vm = new ListModelCategoryViewModel();
            vm.Models = _modelRepository.GetAllModel().Data;

            //-------------------------------------------

            //-------------------------------------------

            return View(vm);
        }

        [HttpPost]
        public ActionResult DeleteModelCategory(int id)
        {
            Feedback feedback = _modelRepository.DeleteModelCategory(id);
            if (feedback.Success)
            {
                // Remove from cache
                ReferenceDataCache.ModelCollection.RemoveAll(i => i.Id == id);

                SetMessage("Manufacturer Category has been deleted successfully", MessageType.Success);
            }
            else
            {
                SetMessage(feedback.Message, MessageType.Error);
            }

            // Redirect to current page after deleting
            return Redirect(Request.UrlReferrer.AbsoluteUri);
        }

        public ViewResult CreateModelCategory()
        {
            var entities = new OrmEntities();
            
            @ViewBag.Device =  new SelectList(entities.Devices, "Id", "Name", null);
            var manu = new SelectList(entities.Manufacturers, "Id", "Name", null); ;
            @ViewBag.Manufacturer = manu;
            @ViewBag.aaa = "aaaaaaaaaeedhdhdheeeeeeeaaaaa";
            return View(new InsertModelCategoryViewModel { Model = new Model() });
        }

        [HttpPost]
        public ActionResult CreateModelCategory(InsertModelCategoryViewModel vm)
        {
            string newUrl = null;
            if (ModelState.IsValid)
            {
                if (vm.file != null)
                {
                    var uploadFeedback = _uploadHandler.UploadModelImage(vm.file);
                    if (!uploadFeedback.Success)
                    {
                        string msg = string.Format("Cập nhật ảnh đại diện không thành công. Chỉ hỗ trợ ảnh định dạng JPG và PNG. " +
                              "Kích thước ảnh không được vượt quá {0}Mb. Nếu lỗi vẫn xảy ra bạn hãy thử lại vào lúc khác.",
                              AppConfigs.UploadImageMaxSize);
                        SetMessage(msg, MessageType.Error);
                        var entities = new OrmEntities();

                        @ViewBag.Device = new SelectList(entities.Devices, "Id", "Name", null);
                        var manu = new SelectList(entities.Manufacturers, "Id", "Name", null); ;
                        @ViewBag.Manufacturer = manu;
                     //   viewmodel = GetPersonalInfo();
                        ViewBag.UploadImageError = msg;
                        return View(vm);
                    }

                    newUrl = string.Format("{0}{1}{2}", uploadFeedback.Data[0], ORM.Common.Constants.ImageUrlsSeparator,
                                                  uploadFeedback.Data[1]);
                    vm.Model.ImageUrl = newUrl;
                  //  CurrentUser.UserInfo.AvatarUrl = newUrl;
                }
                Feedback<Model> feedback = _modelRepository.InsertModel(vm.Model);

                if (feedback.Success)
                {
                    Model exist = ReferenceDataCache.ModelCollection.FirstOrDefault(i => i.Id == feedback.Data.Id);
                    if (exist == null)
                    {
                        ReferenceDataCache.ModelCollection.Add(feedback.Data);
                        ReferenceDataCache.ModelCollection.Sort((c1, c2) => c1.Name.CompareTo(c2.Name));
                    }

                    SetMessage("Model has been inserted successfully", MessageType.Success);

                    return RedirectToAction("ManageModelCategories");
                }
                else
                {
                    SetMessage(feedback.Message, MessageType.Error);
                }
            }

            return View(vm);
        }

        public ActionResult EditModelCategory(int id = 0)
        {
            var feedback = _modelRepository.GetModelCategoryDetails(id);
            if (feedback.Success)
            {
                var mod = feedback.Data;               
                var entities = new OrmEntities();
                @ViewBag.Device = new SelectList(entities.Devices, "Id", "Name", mod.DeviceId);
                var manu = new SelectList(entities.Manufacturers, "Id", "Name", mod.ManufacturerId); ;
                @ViewBag.Manufacturer = manu;
                return View(new InsertModelCategoryViewModel() { Model = feedback.Data });
            }
            else
            {
                SetMessage(feedback.Message, MessageType.Error);
                return RedirectToAction("ManageModelCategories");
            }
        }
        [HttpPost]
        public ActionResult EditModelCategory(InsertModelCategoryViewModel vm)
        {
            string newUrl = null;
            int id = 0;
            if (ModelState.IsValid)
            {
                if (vm.file != null)
                {
                    var uploadFeedback = _uploadHandler.UploadModelImage(vm.file);
                    if (!uploadFeedback.Success)
                    {                       
                        string msg = string.Format("Cập nhật ảnh đại diện không thành công. Chỉ hỗ trợ ảnh định dạng JPG và PNG. " +
                              "Kích thước ảnh không được vượt quá {0}Mb. Nếu lỗi vẫn xảy ra bạn hãy thử lại vào lúc khác.",
                              AppConfigs.UploadImageMaxSize);
                        SetMessage(msg, MessageType.Error);                     
                        EditModelCategory(vm.Model.Id);                        
                        ViewBag.UploadImageError = msg;
                        return View("EditModelCategory");
                    }

                    newUrl = string.Format("{0}{1}{2}", uploadFeedback.Data[0], ORM.Common.Constants.ImageUrlsSeparator,
                                                  uploadFeedback.Data[1]);
                    vm.Model.ImageUrl = newUrl;
                    //  CurrentUser.UserInfo.AvatarUrl = newUrl;
                }
                // Call repository to perform insert
                Feedback<Model> feedback = _modelRepository.UpdateModelCategory(vm.Model);
                if (feedback.Success)
                {
                    Model exist = ReferenceDataCache.ModelCollection.FirstOrDefault(i => i.Id == feedback.Data.Id);
                    if (exist != null)
                    {
                        ReferenceDataCache.ModelCollection.Remove(exist);
                        ReferenceDataCache.ModelCollection.Add(feedback.Data);
                        ReferenceDataCache.ModelCollection.Sort((c1, c2) => c1.Name.CompareTo(c2.Name));
                    }

                    SetMessage("Model Category has been updated successfully", MessageType.Success);

                    return RedirectToAction("ManageModelCategories");
                }
                else
                {
                    SetMessage(feedback.Message, MessageType.Error);
                }
            }

            return View(vm);
        }
        #endregion
        #region Device Categories

        public ViewResult ManageDeviceCategories()
        {
            ListDeviceViewModel vm = new ListDeviceViewModel();
            vm.Devices = _deviceRepository.GetAllDevice().Data;
            return View(vm);
        }

        [HttpPost]
        public ActionResult DeleteDeviceCategory(int id)
        {
            Feedback feedback = _deviceRepository.DeleteDeviceCategory(id);
            if (feedback.Success)
            {
                // Remove from cache
                ReferenceDataCache.DeviceCollection.RemoveAll(i => i.Id == id);

                SetMessage("Device Category has been deleted successfully", MessageType.Success);
            }
            else
            {
                SetMessage(feedback.Message, MessageType.Error);
            }

            // Redirect to current page after deleting
            return Redirect(Request.UrlReferrer.AbsoluteUri);
        }


        public ViewResult CreateDeviceCategory()
        {
            return View(new InsertDeviceCategoryViewModel { Device = new Device() });
        }

        [HttpPost]
        public ActionResult CreateDeviceCategory(InsertDeviceCategoryViewModel vm)
        {
            if (ModelState.IsValid)
            {
                Feedback<Device> feedback = _deviceRepository.InsertDevice(vm.Device);

                if (feedback.Success)
                {
                    Device exist = ReferenceDataCache.DeviceCollection.FirstOrDefault(i => i.Id == feedback.Data.Id);
                    if (exist == null)
                    {
                        ReferenceDataCache.DeviceCollection.Add(feedback.Data);
                        ReferenceDataCache.DeviceCollection.Sort((c1, c2) => c1.Name.CompareTo(c2.Name));
                    }

                    SetMessage("Device has been inserted successfully", MessageType.Success);

                    return RedirectToAction("ManageDeviceCategories");
                }
                else
                {
                    SetMessage(feedback.Message, MessageType.Error);
                }
            }

            return View(vm);
        }

        public ActionResult EditDeviceCategory(int id = 0)
        {
            var feedback = _deviceRepository.GetDeviceCategoryDetails(id);
            if (feedback.Success)
            {
                return View(new InsertDeviceCategoryViewModel { Device = feedback.Data });
            }
            else
            {
                SetMessage(feedback.Message, MessageType.Error);
                return RedirectToAction("ManageDeviceCategories");
            }
        }
        [HttpPost]
        public ActionResult EditDeviceCategory(InsertDeviceCategoryViewModel vm)
        {
            if (ModelState.IsValid)
            {
                // Generate Url friendly name
                //vm.RecipeCategory.NameUrl = vm.RecipeCategory.Name.ToUrlFriendly();

                // Call repository to perform insert
                Feedback<Device> feedback = _deviceRepository.UpdateDeviceCategory(vm.Device);
                if (feedback.Success)
                {
                    Device exist = ReferenceDataCache.DeviceCollection.FirstOrDefault(i => i.Id == feedback.Data.Id);
                    if (exist != null)
                    {
                        ReferenceDataCache.DeviceCollection.Remove(exist);
                        ReferenceDataCache.DeviceCollection.Add(feedback.Data);
                        ReferenceDataCache.DeviceCollection.Sort((c1, c2) => c1.Name.CompareTo(c2.Name));
                    }

                    SetMessage("Device Category has been updated successfully", MessageType.Success);

                    return RedirectToAction("ManageDeviceCategories");
                }
                else
                {
                    SetMessage(feedback.Message, MessageType.Error);
                }
            }

            return View(vm);
        }
        #endregion

        #region GuideType
        public ViewResult ManageGuideType()
        {
            ListGuideTypesViewModel vm = new ListGuideTypesViewModel();
            vm.GuideTypes = _guideTypeRepository.GetAllGuideType().Data;
            return View(vm);
        }


        [HttpPost]
        public ActionResult DeleteGuideType(int id)
        {
            Feedback feedback = _guideTypeRepository.DeleteGuideTypeCategory(id);
            if (feedback.Success)
            {
                // Remove from cache
                ReferenceDataCache.GuideTypeCollection.RemoveAll(i => i.Id == id);

                SetMessage("GuideType Category has been deleted successfully", MessageType.Success);
            }
            else
            {
                SetMessage(feedback.Message, MessageType.Error);
            }

            // Redirect to current page after deleting
            return Redirect(Request.UrlReferrer.AbsoluteUri);
        }

        public ViewResult CreateGuideType()
        {
            return View(new InsertGuideTypeViewModel() { GuideType = new GuideType() });
        }

        [HttpPost]
        public ActionResult CreateGuideType(InsertGuideTypeViewModel vm)
        {
            if (ModelState.IsValid)
            {
                Feedback<GuideType> feedback = _guideTypeRepository.InsertGuideType(vm.GuideType);

                if (feedback.Success)
                {
                    GuideType exist = ReferenceDataCache.GuideTypeCollection.FirstOrDefault(i => i.Id == feedback.Data.Id);
                    if (exist == null)
                    {
                        ReferenceDataCache.GuideTypeCollection.Add(feedback.Data);
                        ReferenceDataCache.GuideTypeCollection.Sort((c1, c2) => c1.Name.CompareTo(c2.Name));
                    }

                    SetMessage("GuideType has been inserted successfully", MessageType.Success);

                    return RedirectToAction("ManageGuideType");
                }
                else
                {
                    SetMessage(feedback.Message, MessageType.Error);
                }
            }

            return View(vm);
        }

        public ActionResult EditGuideType(int id = 0)
        {
            var feedback = _guideTypeRepository.GetGuideTypeCategoryDetails(id);
            if (feedback.Success)
            {
                return View(new InsertGuideTypeViewModel() { GuideType = feedback.Data });
            }
            else
            {
                SetMessage(feedback.Message, MessageType.Error);
                return RedirectToAction("ManageGuideType");
            }
        }
        [HttpPost]
        public ActionResult EditGuideType(InsertGuideTypeViewModel vm)
        {
            if (ModelState.IsValid)
            {
                // Call repository to perform insert
                Feedback<GuideType> feedback = _guideTypeRepository.UpdateGuideTypeCategory(vm.GuideType);
                if (feedback.Success)
                {
                    GuideType exist = ReferenceDataCache.GuideTypeCollection.FirstOrDefault(i => i.Id == feedback.Data.Id);
                    if (exist != null)
                    {
                        ReferenceDataCache.GuideTypeCollection.Remove(exist);
                        ReferenceDataCache.GuideTypeCollection.Add(feedback.Data);
                        ReferenceDataCache.GuideTypeCollection.Sort((c1, c2) => c1.Name.CompareTo(c2.Name));
                    }

                    SetMessage("GuideType has been updated successfully", MessageType.Success);

                    return RedirectToAction("ManageGuideType");
                }
                else
                {
                    SetMessage(feedback.Message, MessageType.Error);
                }
            }

            return View(vm);
        }

        #endregion

    }
}
